<template>
  <a-card :bordered="false">
    <a-form-model ref="dynamicValidateForm" :model="dynamicValidateForm" v-bind="formItemLayoutWithOutLabel">
      <a-form-model-item
        label="所属单位"
        v-bind="formItemLayout"
        prop="achievementUnit"
        :rules="{
          required: true,
          message: '所属单位不能为空',
          trigger: 'blur',
        }"
      >
        <a-input v-model="dynamicValidateForm.achievementUnit" />
      </a-form-model-item>
      <a-form-model-item label="意向转化地域" v-bind="formItemLayout">
        <j-multi-select-tag
          v-model="dynamicValidateForm.provinces"
          :options="dictOptions"
          placeholder="请选择意向转化地域"
        >
        </j-multi-select-tag>
      </a-form-model-item>

      <a-form-model-item
        v-for="(domain, index) in dynamicValidateForm.reportAchievementListBOS"
        :key="domain.key || domain.id"
        v-bind="formItemLayout"
        :label="'待转化成果' + (index + 1)"
        :prop="'reportAchievementListBOS.' + index + '.achievement'"
        :rules="{
          required: true,
          message: '待转化成果描述不能为空',
          trigger: 'blur',
        }"
      >
        <a-input
          v-model="domain.achievement"
          type="textarea"
          placeholder="请输入待转化成果描述，如开发高温高压深水柔性立管，可应用于深水油气开发。"
          style="width: 60%; margin-right: 8px"
          :disabled="!domain.isEditing"
        />
        <template v-if="!domain.isEditing">
          <a-button type="primary" style="margin-right: 8px" @click="editItem(domain)">编辑</a-button>
        </template>
        <template v-else>
          <a-button type="primary" style="margin-right: 8px" @click="saveItem(domain)">保存</a-button>
        </template>
        <a-icon
          v-if="dynamicValidateForm.reportAchievementListBOS.length > 1"
          class="dynamic-delete-button"
          type="minus-circle-o"
          :disabled="dynamicValidateForm.reportAchievementListBOS.length === 1"
          @click="removeDomain(domain)"
        />
      </a-form-model-item>
      <a-form-model-item v-bind="formItemLayoutWithOutLabel">
        <a-button type="dashed" style="width: 60%" @click="addDomain">
          <a-icon type="plus" /> 添加转化成果描述
        </a-button>
      </a-form-model-item>
      <a-form-model-item v-bind="formItemLayoutWithOutLabel">
        <a-button
          type="primary"
          html-type="submit"
          :disabled="findIsEditing()"
          @click="submitForm('dynamicValidateForm')"
        >
          生成报告
        </a-button>
      </a-form-model-item>
    </a-form-model>
  </a-card>
</template>

<script>
import { deleteAction, getAction, postAction, downFile, getFileAccessHttpUrl } from '@/api/manage'
export default {
  name: 'Error',
  components: {},
  data() {
    return {
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 4 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
      },
      formItemLayoutWithOutLabel: {
        wrapperCol: {
          xs: { span: 24, offset: 0 },
          sm: { span: 20, offset: 4 },
        },
      },
      dynamicValidateForm: {
        reportAchievementListBOS: [],
      },
      reportId: this.$route.query.id,
      url: {
        detail: '/report4/details',
        province: '/report4/dict/province',
        saveAchievement: '/report4/editOrSaveAchievement',
        removeAchievement: '/report4/removeAchievement',
        editDetails: '/report4/editDetails',
      },
      dictOptions: [],
    }
  },
  mounted() {
    this.getDetail()
  },
  created() {
    this.initDict()
  },
  beforeRouteUpdate(to, from, next) {
    if (to.fullPath !== from.fullPath) {
      this.reportId = to.query.id
      this.getDetail()
    }
    next()
  },
  methods: {
    findIsEditing() {
      let reportAchievementListBOS = this.dynamicValidateForm.reportAchievementListBOS
      const isEditingPresent = reportAchievementListBOS.some((item) => item.isEditing === true)

      return isEditingPresent
    },
    submitForm(formName) {
      if (this.dynamicValidateForm.reportAchievementListBOS.length == 0) {
        this.$message.warning('请添加至少一项成果描述')
        return false
      }
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            reportId: this.$route.query.id,
            provinces: this.dynamicValidateForm.provinces,
            achievementUnit: this.dynamicValidateForm.achievementUnit,
          }
          postAction(this.url.editDetails, params).then((res) => {
            if (res.success) {
              this.$router.push({
                path: '/tabs4/list',
                query: { reportId: this.$route.query.id },
              })
            } else {
              that.$message.warning(res.message)
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    getDetail() {
      let id = this.reportId
      var that = this
      getAction(that.url.detail + '/' + id).then((res) => {
        if (res.success) {
          // 重构reportAchievementListBOS数组 添加isEditing 编辑控制功能--------
          let reportAchievementListBOS = []
          if (res.result.reportAchievementListBOS.length > 0) {
            reportAchievementListBOS = res.result.reportAchievementListBOS.map((e) => {
              return {
                ...e,
                isEditing: false,
              }
            })
          }
          this.dynamicValidateForm = res.result || {}
          // -------------------------------------------------------------------
          this.dynamicValidateForm.reportAchievementListBOS = reportAchievementListBOS

          //重新计算分页问题
        } else {
        }
      })
    },
    initDict() {
      getAction(this.url.province).then((res) => {
        if (res.success) {
          console.log('1111122222', res)

          this.dictOptions = res.result.map((e) => {
            return {
              label: e.description,
              value: e.description,
            }
          })
          console.log(this.dictOptions)
        }
      })
    },
    handleDelete: function () {},
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    removeDomain(item) {
      if (item.id) {
        deleteAction(this.url.removeAchievement + '/' + item.id).then((res) => {
          if (res.success) {
            //重新计算分页问题
            this.deleteReportAchievementList(item)
          } else {
            that.$message.warning(res.message)
          }
        })
      } else {
        this.deleteReportAchievementList(item)
      }
    },
    deleteReportAchievementList(item) {
      let index = this.dynamicValidateForm.reportAchievementListBOS.indexOf(item)
      if (index !== -1) {
        this.dynamicValidateForm.reportAchievementListBOS.splice(index, 1)
      }
    },
    editItem(domain) {
      domain.isEditing = true
    },

    saveItem(domain) {
      let params = {
        ...domain,
        reportId: this.$route.query.id,
        provinces: this.dynamicValidateForm.provinces,
        achievementUnit: this.dynamicValidateForm.achievementUnit,
      }
      postAction(this.url.saveAchievement, params).then((res) => {
        if (res.success) {
          domain.isEditing = false
        } else {
          that.$message.warning(res.message)
        }
      })

      // 这里可以添加保存到后端的逻辑
    },
    addDomain() {
      this.dynamicValidateForm.reportAchievementListBOS.push({
        achievement: '',
        key: Date.now(),
        isEditing: false, // 新增字段，控制编辑状态
      })
    },
  },
}
</script>

<style scoped>
</style>